<template>
    <div style="height: 60px">
        <div class="botoomControl">
            <audio :src="musicUrl" ref="audioPlayer" autoplay @play="changeState(true)" @pause="changeState(false)"
                @timeupdate="timeupdate"></audio>
            <!-- 左边 -->
            <div class="left">
                <div class="avatar" @click="store.changeMusicDetailCardState()">
                    <img :src="musicDetail.al.picUrl" v-if="musicDetail.al" :draggable="false" alt="">
                    <img src="../static/logo-samll.png" v-else :draggable="false" alt="" />
                </div>
                <div class="musicInfo">
                    <div class="musicName" v-if="musicDetail && musicDetail.name">{{musicDetail.name}}</div>
                    <div class="singer" v-if="musicDetail && musicDetail.name">{{musicDetail.ar[0].name}}</div>
                </div>
            </div>
            <div class="center">
                <div class="buttons">
                    <span>
                        <i class="iconfont icon-xunhuan"></i>
                    </span>
                    <span>
                        <i class="iconfont icon-shangyishou"></i>
                    </span>
                    <span>
                        <i class="iconfont icon-bofang play" v-if="!store.isPlay" @click="clickPlay"></i>
                        <i class="iconfont icon-zanting play" v-else @click="clickPause"></i>

                    </span>
                    <span>
                        <i class="iconfont icon-xiayishou"></i>
                    </span>
                    <span>
                        <i class="iconfont icon-xihuan"></i>
                    </span>
                </div>
                <div class="progressBar">
                    <span class="currentime">{{currenTimeStr}}</span>
                    <el-slider class="progressSlider" v-model="timeProgress" @change="changeProgress"
                        :show-tooltip="false" />
                    <span class="titalTime">{{duration}}</span>
                </div>
            </div>
            <div class="right">
                <div class="volumeControl">
                    <i class="iconfont icon-yinliang" v-if="!isMuted" @click="changeMuted"></i>
                    <i class="iconfont icon-jingyin" v-else @click="changeMuted"></i>
                    <el-slider class="volumeSlider" v-model="volume" @input="changeVolume" />
                </div>
                <div class="playList">
                    <i class="iconfont icon-unorderedlist"></i>

                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, watch, onMounted, computed } from 'vue'
import request from '../api'
import useStore from '../store/idnex'
import { ElMessage } from 'element-plus'
import { handleMusicTime, returnSecond } from '../utils/utils'
import mitt from '../utils/eventBus'

let lastSecond = 0
// 总时长的秒数
let durationNum = 0
let volumeTmp = ref(0)
const store = useStore()
// 音乐控件对象
const audioPlayer = ref(null)

const musicDetail = ref({})
const musicUrl = ref('')
const musicList = ref([])
const currentMusicIndex = ref(0)
// 音乐总时长
const duration = ref('00:00')

// 当前播放时间
const currentTime = ref(0)
const currenTimeStr = ref('00:00')
watch(currentTime, (newVal) => {
    currenTimeStr.value = handleMusicTime(newVal, null)
})
// 进度条的位置
const timeProgress = ref(0)
// 音量
const volume = ref(30)
// 是否静音
const isMuted = ref(false)


//根据id找到musicList中对应的musicDetail
const getMusicDetailFromMusic = () => {

    let index = musicList.value.findIndex(item => item.id == store.musicId)
    if (index !== -1) {
        // 记录当前音乐的index
        currentMusicIndex.value = index
        store.updateCurrentIndex(index)
        musicDetail.value = musicList.value[index]
        // 直接从audio标签中的duration属性拿时长会有请求时差问题,所以直接在musicInfo中拿
        duration.value = musicList.value[index].dt
    }
}

//请求歌曲url
const getMusicDetail = async (id) => {
    let res = await request('/song/url', { id })
    if (res.data.data[0] == null) {
        ElMessage.error('该歌曲暂无版权！')
        return
    }
    musicUrl.value = res.data.data[0].url

}



//播放音乐
const playMusic = () => {
    audioPlayer.value.play()
}

// 暂停音乐
const pauseMusic = () => {
    audioPlayer.value.pause()
    musicList.value = store.musicList
}

//点击播放按钮
const clickPlay = () => {
    // 如果audio没有音乐链接直接返回
    if (!musicUrl.value) return
    // 将播放状态改为true
    store.changePlayState(true)
}
//点击暂停按钮
const clickPause = () => {
    store.changePlayState(false)
}

//调节音量
const changeVolume = (value) => {
    // audio标签的volume属性值范围0-1,input事件，实时触发
    audioPlayer.value.volume = value / 100
}
//点击静音
const changeMuted = () => {
    // 如果已经静音则点击还原音量
    if (isMuted.value) {
        volume.value = volumeTmp.value
        changeVolume(volume.value)
    } else {
        // 如果当前未静音，先保存当前音量，再将音量置0
        volumeTmp.value = volume.value
        volume.value = 0
        changeVolume(0)
    }
    isMuted.value = !isMuted.value
}

//audio开始或暂停播放的 回调，在store中改变状态
const changeState = (state) => {
    store.changePlayState(state)
}

// 实时播放时间改变的回调
const timeupdate = () => {
    let time = audioPlayer.value.currentTime
    // 触发歌词偏移的事件,用来实时显示歌词
    mitt.emit("setoffSet")
    store.updataCurrentTime(time)
    time = Math.floor(time)
    if (time !== lastSecond) {
        lastSecond = time
        currentTime.value = time
        // 计算进度条的位置
        timeProgress.value = Math.floor((time / durationNum) * 100)
    }
}
//拖动音乐进度条的回调
const changeProgress = (value) => {
    // console.log(value);
    currentTime.value = Math.floor(durationNum * (value / 100))
    //改变audio当前实际播放时间
    audioPlayer.value.currentTime = currentTime.value
}

//监听store中musicId的变化
watch(
    () => {
        return store.musicId
    },
    (newId) => {
        // 先暂停播放音乐
        pauseMusic()
        musicList.value = store.musicList
        getMusicDetailFromMusic()
        getMusicDetail(newId)
        durationNum = returnSecond(duration.value);
    }
)

watch(() => { return store.isPlay }, (isPlay) => {
    if (isPlay) {
        playMusic()
    } else {
        pauseMusic()
    }
})
</script>

<style lang="scss" scoped>
audio {
    display: none;
}

.botoomControl {
    border-top: 1px solid #ddd;
    width: 100%;
    height: 60px;
    min-width: 800px;
    position: fixed;
    bottom: 0;
    left: 0;
    display: flex;
    z-index: 100;
    background-color: #fff;
    justify-content: space-between;
    padding: 6px 10px;
    align-items: center;

    .iconfont {
        cursor: pointer;
    }

    .left {
        display: flex;
        align-items: center;

        .avatar {
            border-radius: 5px;
            margin-right: 10px;
            cursor: pointer;
            overflow: hidden;

            img {
                width: 50px;
                height: 50px;
            }
        }

        .musicInfo {
            color: rgb(37, 37, 37);

            .musicName {
                margin-bottom: 4px;
                width: 100%;
                font-size: 14px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }

            .singer {
                width: 100%;
                font-size: 13px;
            }
        }
    }

    .center {
        display: flex;
        flex-direction: column;
        align-items: center;
        position: relative;
        margin-left: 90px;

        .buttons {
            position: absolute;
            bottom: 0px;
            display: flex;
            align-items: center;
            height: 13px;

            span {
                width: 60px;
                text-align: center;
                line-height: 100%;


                .icon-xunhuan {
                    font-size: 25px;
                }

                .icon-shangyishou {
                    font-size: 25px;
                }

                .play {
                    font-size: 30px;

                }

                .icon-xiayishou {
                    font-size: 25px;
                }

                .icon-xihuan {
                    font-size: 20px;
                }
            }
        }

        .progressBar {
            position: absolute;
            bottom: 20pxpx;
            display: flex;

            .progressSlider {
                width: 400px;
                transform: scale(0.9);
            }

            span {
                font-size: 13px;
                color: #aaa;
                width: 30px;
                text-align: center;
                display: flex;
                align-items: center;
            }
        }
    }

    .right {
        margin-right: 75px;
        display: flex;
        align-items: center;

        .volumeControl {
            display: flex;
            align-items: center;
            margin-right: 20px;

            .icon-yinliang {
                font-size: 20px;
                margin-right: 10px;
            }
            .icon-jingyin{
                font-size: 20px;
                    margin-right: 10px;
                    // 由于音量图标和静音图标不一样大，有强迫症，放大静音图标1.1倍
                    transform: scale(1.1);
            }


            .volumeSlider {
                width: 80px;
            }
        }

        .playList {
            .icon-unorderedlist {
                font-size: 25px;
            }
        }
    }
}
</style>
